import api
from DBAction import DBAction
from juju import Juju


def get_live_list(livemap):
    url = "https://pocketapi.48.cn/live/api/v1/live/getLiveList"
    params = {"groupId": 0, "debug": True, "next": 0, "record": False}
    response = api.post(url, params)
    if response['status'] == 200:
        liveList = response['content']['liveList']
        idlist = []
        for data in liveList:
            # print(data)
            liveid = data['liveId']
            idlist.append(liveid)
            if liveid not in livemap:
                live = Live(liveid)
                live.get_live_one()
                api.wait_random_time(0.5)
                livemap[liveid] = live
        deletelist = []
        for id in livemap:
            if id not in idlist:
                deletelist.append(id)
        for id in deletelist:
            livemap[id].get_live_result()
            api.wait_random_time(2)
            del livemap[id]


def get_record_list():
    url = "https://pocketapi.48.cn/live/api/v1/live/getLiveList"
    params = {"debug": True, "next": 0, "record": True}
    response = api.post(url, params)
    if response['status'] == 200:
        print(response)


class Live:
    def __init__(self, live_id):
        self.live_id = live_id
        self.memberid = 0
        self.name = ''

    def get_live_one(self):
        url = "https://pocketapi.48.cn/live/api/v1/live/getLiveOne"
        params = {
            "liveId": str(self.live_id)
        }
        response = api.post(url, params)
        if response['status'] == 200:
            # roomId = response['content']['roomId']
            onlineNum = response['content']['onlineNum']
            liveType = response['content']['liveType']  # 1 zhibo 2diantai
            # review = response['content']['review']  # 是否为录播，录播就可以取结果了
            # playStreamPath = response['content']['playStreamPath'] # 录播状态为回放地址
            self.memberid = response['content']['user']['userId']
            title = response['content']['title']
            cover = response['content']['coverPath']
            time = api.convert_timestamp_to_timestr(response['content']['ctime'])
            self.name = str(response['content']['user']['userName'])
            if '-' in self.name:  # userName=SNH48-xxx
                self.name = self.name.split('-')[1]

            db = DBAction('pocket48')
            # 检查member是否存在在表里
            result = db.data_inquiry_all('select count(1) from member where memberid=%s', self.memberid)
            if result[0][0] == 0:
                roomid = response['content']['roomId']
                db.data_operate("insert into member(memberid,roomid,name) values(%s,%s,%s)",
                    (self.memberid, roomid, self.name))

            result = db.data_inquiry_all('select count(1) from live where liveid=%s', self.live_id)
            if result[0][0] == 0:
                db.data_operate("insert into live(liveid,memberid,start_time,title,type,cover,liveonline) values(%s,%s,%s,%s,%s,%s,%s)",
                                (self.live_id, self.memberid, time, title, liveType, cover, onlineNum))

    def get_live_result(self):
        url = "https://pocketapi.48.cn/live/api/v1/live/result"
        params = {
            "liveId": str(self.live_id)
        }
        response = api.post(url, params)
        if response['status'] == 200:
            length = int(response['content']['liveTime']) / 1000
            totalMoney = response['content']['totalMoney']
            liveOnline = response['content']['liveOnline']

            db = DBAction('pocket48')
            if str(totalMoney) != '0':
                topuser = response['content']['topUser']['user']
                fanid = topuser['userId']
                name = topuser['userName']
                level = topuser['level']
                juju = Juju(fanid, name, level)
                juju.check()  # 确保存在
                db.data_operate("update live set length=%s,fanid=%s,totalmoney=%s,liveonline=%s where liveid=%s",
                                (length, fanid, totalMoney, liveOnline, self.live_id))
            else:
                db.data_operate("update live set length=%s,totalmoney=%s,liveonline=%s where liveid=%s",
                                (length, totalMoney, liveOnline, self.live_id))
